# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(randomForest)
library(Boruta)
library(magrittr)
library(e1071)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--config", default = "calculate_config.json", type = "character", help = "config file")

)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote")) %>%
  mutate(ClassNote = as.character(ClassNote))

head(sampleInfo)

parent <- paste0("./")
createWhenNoExist(parent)

fileName <- opt$i
if (!file.exists(fileName)) {
  quit(status = 0)
}

data <- read_tsv(fileName) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  inner_join(sampleInfo, by = c("SampleID")) %>%
  column_to_rownames("SampleID") %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote))) %>%
  as.data.frame()

x <- data %>% select(-c("ClassNote"))
y <- data$ClassNote

configJson <- fromJSON(opt$config)
kernel <- configJson$kernel
cost <- configJson$cost %>%
  as.numeric()
tolerance <- configJson$tolerance %>%
  as.numeric()
epsilon <- configJson$epsilon %>%
  as.numeric()
gamma <- configJson$gamma %>%
  as.numeric()
coef0 <- configJson$coef0 %>%
  as.numeric()
degree <- configJson$degree %>%
  as.numeric()

finalGamma <- if (is.na(gamma)) {
  if (is.vector(x)) 1 else 1 / ncol(x)
}else {
  gamma
}
svmRs <- svm(x, y, type = 'C', kernel = kernel, cost = cost, tolerance = tolerance, epsilon = epsilon,
             gamma = finalGamma, coef0 = coef0, degree = degree,scale=F)
unclass(svmRs)
imp <- (t(svmRs$coefs) %*% svmRs$SV)[1,]^2
names(imp) <- colnames(x);
impData <- imp %>%
  as.data.frame() %>%
  rownames_to_column("Metabolite") %>%
  set_colnames(c("Metabolite", "Value")) %>%
  arrange(Value) %>%
  mutate(Metabolite = factor(Metabolite, levels = unique(Metabolite)))
impData
print(head(impData))

plotData <- impData
outData <- plotData %>%
  arrange(desc(Value)) %>%
  rename(`SVM-RFE` = Value)
outFileName <- paste0(parent, "/SVM_Imp_Rank.csv")
write.csv(outData, outFileName, row.names = F)






